//
//  ZZTongUIEngine.m
//  V-POS
//
//  Created by handpay on 12-10-24.
//  Copyright (c) 2012年 handpay. All rights reserved.
//

#import "ZZTongUIEngine.h"
#import "DefineUtil.h"
#import <CoreLocation/CoreLocation.h>
#import <QuartzCore/CAAnimation.h>
#import "HPAbstrictViewController.h"
#import "CategoryUtil.h"
#import "HPWelcomeViewController.h"
#import "VPOSLocationManager.h"
//#import "HPSetUrlViewController.h"

@interface ZZTongUIEngine () {
}

@property (nonatomic, retain) ZZTongAlertWaitingView *alertView;
@property (nonatomic, retain) ZZTongAlertWaitingView *waitingView;

@end


@implementation ZZTongUIEngine



// 移除欢迎页面
- (void) removeWelcomeScreen
{
    NSMutableArray* viewControllerArray = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    UIViewController* tempViewController = [viewControllerArray objectAtIndex:0];
    if ([tempViewController isKindOfClass:[HPWelcomeViewController class]]) {
        [viewControllerArray removeObjectAtIndex:0];
        self.navigationController.viewControllers = viewControllerArray;
    }
}
- (void) removeSetUrlScreen
{
//    NSMutableArray* viewControllerArray = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
//    UIViewController* tempViewController = [viewControllerArray objectAtIndex:0];
//    if ([tempViewController isKindOfClass:[HPSetUrlViewController class]]) {
//        [viewControllerArray removeObjectAtIndex:0];
//        self.navigationController.viewControllers = viewControllerArray;
//    }
}

#pragma mark - 公共方法

- (void) uiShowTipsAlertWithMessage:(NSString *)message{
    [self uiShowTipsAlertWithTitle:@"提示" message:message];
}

- (void) uiShowTipsAlertWithTitle:(NSString *)title message:(NSString *)message
{
    ZZTongAlertWaitingView* tempAlertView = [[ZZTongAlertWaitingView alloc] initAlertViewWithTitleTagImageName:@"alert_title_tag.png" title:title message:message];
    self.alertView = tempAlertView;
    [tempAlertView release];
    [self.alertView addButtonWithTitle:@"确定"];
    [self.alertView show];
}
- (void)clickFunc{
    
}
- (void) showAlertWithTitleTagImageName:(NSString *)titleTagImageName title:(NSString *)title message:(NSString *)message commands:(NSArray *)commands
{
    ZZTongAlertWaitingView* tempAlertView = [[ZZTongAlertWaitingView alloc] initAlertViewWithTitleTagImageName:titleTagImageName title:title message:message];
    self.alertView = tempAlertView;
    [tempAlertView release];
    
    if(!commands)
    {
        for (NSDictionary * command in commands)
        {
            NSString * label = [command objectForKey:@"label"];
            id obj = [command objectForKey:@"delegate"];
            NSString * clickFunc = [command objectForKey:@"function"];
            SEL func = @selector(onClick:);
            if (clickFunc)
            {
                func = @selector(clickFunc);
            }
            UIButton * button = [self.alertView addButtonWithTitle:label];
            [button addTarget:obj action:func forControlEvents:UIControlEventTouchUpInside];
        }
    }
    [self.alertView show];
}
- (void) onClick:(UIButton *) sender{
    [self dismissAlertOrWaitingView];
}
- (void) showWaitingWithTitle:(NSString *)title
{
    if (self.waitingView) {
        [self.waitingView setTitle:title];
        return;
    }
    
    ZZTongAlertWaitingView* tempWaitingView = [[ZZTongAlertWaitingView alloc] initWaitingViewWithTitle:title];
    self.waitingView = tempWaitingView;
    [tempWaitingView release];
    
    [self.waitingView show];
}

- (void) dismissAlertOrWaitingView
{
    if (self.alertView) {
        [self.alertView dismiss];
        self.alertView = nil;
    }
    if (self.waitingView) {
        [self.waitingView dismiss];
        self.waitingView = nil;
    }
}


#pragma mark - VPOSAlertWaitingViewDelegate

- (void) dismissAlertView:(ZZTongAlertWaitingView *)alertView_
{
    if (self.alertView == alertView_) {
        self.alertView = nil;
    }
}
- (void) showSetUrlScreen
{
//    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
//    
//    HPSetUrlViewController * welScreen = [[HPSetUrlViewController alloc] initWithNibName:@"HPSetUrlViewController" bundle:nil];
//    [self.navigationController pushViewController:welScreen animated:NO];
//    [welScreen release];
}

- (void) showWelcomeScreen
{
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    
    HPWelcomeViewController* welScreen = [[HPWelcomeViewController alloc] initWithNibName:SCR_WELCOME bundle:nil];
    [self.navigationController pushViewController:welScreen animated:NO];
    [welScreen release];
}

- (void)showAlert:(NSDictionary *)dic{
    
}

- (void)dimissAlert{
    
}


- (id)init{
    self = [super init];
    if (self) {
//        self.isLogin = YES;
        
        [self createNavigationContoller];
       
        
//        NSArray* array = @[@[@"", @"收款"],
//                           @[@"", @"流水"],
//                           @[@"", @"商户"],
//                           @[@"", @"更多"]];
//        UITabBarController* tabBar = [self createTabBar:array];
        
        
    }
    return self;
}

- (void)setBarColor:(UINavigationController*)nav{
    if ([nav.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
        nav.navigationBar.barTintColor = kTitleFontColor;
    }else{
        nav.navigationBar.tintColor = kTitleFontColor;
    }
}

- (void)createNavigationContoller{
    UINavigationController* nav = [[UINavigationController alloc] init];
    [self setBarColor:nav];
    self.navigationController = nav;
    [nav release];
    
    [UIApplication sharedApplication].keyWindow.rootViewController = self.navigationController;
}

-(void)showScreen:(UIViewController *)viewController{
    UINavigationController* tempNav = [self getCurrentNavigation];
    
    [self removeLastNotSaveViewController:tempNav];
    
    if ([viewController isKindOfClass:[HPAbstrictViewController class]]) {
//        HPAbstrictViewController* absViewController = (HPAbstrictViewController*)viewController;
//        
//        UIViewController* lastViewController = [tempNav topViewController];
//        lastViewController.hidesBottomBarWhenPushed = absViewController.hideBottomBar;
//        
//        [tempNav pushViewController:viewController animated:YES];
//        
//        if ([lastViewController isKindOfClass:[HPAbstrictViewController class]]) {
//            HPAbstrictViewController* tempViewController = (HPAbstrictViewController*)lastViewController;
//            lastViewController.hidesBottomBarWhenPushed = tempViewController.hideBottomBar;
        HPAbstrictViewController* absViewController = (HPAbstrictViewController*)viewController;
        
        viewController.hidesBottomBarWhenPushed = absViewController.hideBottomBar;
        
        [tempNav pushViewController:viewController animated:YES];
    }else{
        [tempNav pushViewController:viewController animated:YES];
    }
}

- (UINavigationController*)getCurrentNavigation{
    if (self.tabBarController) {
        return (UINavigationController*)[self.tabBarController.viewControllers objectAtIndex:self.tabBarController.selectedIndex];
    }
    
    if (self.navigationController) {
        return self.navigationController;
    }
    
    return nil;
}

- (void)popToScreen:(Screen*)viewController animations:(BOOL)animations
{
    UINavigationController* tempNav = [self getCurrentNavigation];
     [tempNav popToViewController:viewController animated:animations];
}

- (void)popToRootScreen:(BOOL)animations{
    UINavigationController* tempNav = [self getCurrentNavigation];
    
    [tempNav popToRootViewControllerAnimated:animations];
}
- (void)popToLoginScreen:(BOOL)animations{
    self.tabBarController = nil;
    [self.navigationController popToRootViewControllerAnimated:animations];
}
- (void)popScreen:(int)backNum animations:(BOOL)animations
{
    UINavigationController* tempNav = [self getCurrentNavigation];
    
    NSArray* viewControllers = tempNav.viewControllers;
    int controllerCount = (int)viewControllers.count;
    if (controllerCount <= 1) {
        if (![tempNav isEqual:self.navigationController]) {
            self.tabBarController = nil;
            [self.navigationController popViewControllerAnimated:animations];
        }
        return;
    }
    
    if (backNum >= controllerCount) {
        backNum = controllerCount - 1;
    }
    UIViewController *viewController = [viewControllers objectAtIndex:(controllerCount - backNum - 1)];
   
    [tempNav popToViewController:viewController animated:animations];
    return;
}

- (UIViewController*)topScreen{
    
    UINavigationController* tempNav = [self getCurrentNavigation];
    
    Screen *currentScreen = (Screen *)[tempNav topViewController];

    if (!currentScreen.isDisappearing){
        return currentScreen;
    }else{
        int count = (int)tempNav.viewControllers.count;
        if (count > 1) {
            return (Screen *)[tempNav.viewControllers objectAtIndex:(count - 2)];
        }
    }
    
    return [tempNav topViewController];
}

-(NSArray*)getCurrentControllerArray{
    UINavigationController* tempNav = [self getCurrentNavigation];
    
    return tempNav.viewControllers;
}

- (UITabBarItem*)createItem:(NSString*)screenName{
    
    
    NSString* imgName = nil;
    NSString* titleName = nil;
    if ([screenName isEqualToString:SCR_COLLECT_MONEY]) {
        imgName = @"collect";
        titleName = @"收款";
    }else if ([screenName isEqualToString:SCR_ACCOUNT_INDEX]){
        imgName = @"user";
        titleName = @"账户";
    }else{
        imgName = @"function";
        titleName = @"功能";
    }
    
    
    UIImage* tabImag = [UIImage imageNamed:imgName];
    UIImage* tabSelectImag = [UIImage imageNamed:[NSString stringWithFormat:@"%@hover.png", imgName]];
    
    UITabBarItem* barItem = nil;
    if (([[[UIDevice currentDevice] systemVersion]doubleValue]>=7.0)) {
        
        barItem = [[UITabBarItem alloc] initWithTitle:titleName image:tabImag selectedImage:tabSelectImag];
        [barItem setFinishedSelectedImage:tabSelectImag withFinishedUnselectedImage:tabImag];
        [barItem.selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }else{
        barItem = [[UITabBarItem alloc] initWithTitle:titleName image:tabImag tag:0];
        [barItem setFinishedSelectedImage:tabSelectImag withFinishedUnselectedImage:tabImag];
    }
    
//    if ([barItem respondsToSelector:@selector(setTitlePositionAdjustment:)]) {
//        [barItem setTitlePositionAdjustment:UIOffsetMake(0, 3)];
//    }
    return [barItem autorelease];
}

- (UINavigationController*)getNav:(NSString*)screenName{
    Screen* scr = [HPUIENG createScreen:screenName params:nil];
    scr.tabBarItem = [self createItem:screenName];
    
    UINavigationController* nav = [[UINavigationController alloc] initWithRootViewController:scr];
    
    [self setBarColor:nav];
    
    return [nav autorelease];
}

- (void)showScreenByIndex:(NSInteger)index params:(NSDictionary *)params{
    UITabBarController* tab = [[UITabBarController alloc] init];
    tab.delegate = self;
    NSArray* controllerList = @[[self getNav:SCR_ACCOUNT_INDEX], [self getNav:SCR_COLLECT_MONEY], [self getNav:SCR_FUNCTION]];
    tab.viewControllers = controllerList;
    
    //    UIView * mView=[[UIView alloc] initWithFrame:CGRectMake(0, 1, 320, 48)];//这是整个tabbar的颜色
    //    [mView setBackgroundColor:UIColorFromRGB(0xF6F6F6)];
    //    [tab.tabBar insertSubview:mView atIndex:1];
    //    [mView release];
    
    [[UITabBar appearance] setBackgroundColor:UIColorFromRGB(0xF6F6F6)];
    [tab setSelectedIndex:index];
    self.tabBarController = tab;
    [tab release];
    
    
    [self removeLastNotSaveViewController:self.navigationController];
    
    self.navigationController.navigationBarHidden = YES;
    [self.navigationController pushViewController:self.tabBarController animated:YES];
    if (params) {
        NSArray* viewArray = [params objectForKey:KEY_SCR_VIEWS];
        for (NSDictionary* viewInfo in viewArray) {
            NSInteger tempIndex = [[viewInfo objectForKey:KEY_SCR_INDEX] integerValue];
            if (tempIndex < 0 || tempIndex >= controllerList.count) {
                continue;
            }
            
            NSString* scrId = [viewInfo objectForKey:KEY_SCR_ID];
            NSDictionary* scrParams = [viewInfo objectForKey:KEY_SCR_PARAMS];
            [HPUIENG showScreen:scrId params:scrParams];
        }
    }
    
    
}
- (void)removeLastNotSaveViewController:(UINavigationController*)nav{
    NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:nav.viewControllers];
    
    UIViewController *lastViewController = [viewControllers lastObject];
    if ([lastViewController isKindOfClass:[HPAbstrictViewController class]] && !(((HPAbstrictViewController *)lastViewController).canSave)) {
        [viewControllers removeLastObject];
        [nav setViewControllers:viewControllers];
    }
}

- (void)showNetWaiting{
    [HPUIENG showWaiting:@"正在加载中..."];
}

- (void)hideNavigationBar:(BOOL)hidden{
    UINavigationController* nav = [self getCurrentNavigation];
    [nav setNavigationBarHidden:hidden];
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    [NOTIFICATION postNotificationName:TableBarSelectedIndexChangeNotificationKey object:@(tabBarController.selectedIndex)];
}

- (void)dealloc {
    
    self.navigationController = nil;
    self.tabBarController = nil;
    self.alertView = nil;
    self.waitingView = nil;
    
    [super dealloc];
}
#pragma mark - hp util delegate
- (void) userCurrentLocationSuccess:(void (^)(CLLocationCoordinate2D userLocationCoordinate,NSDictionary *address))success fail:(void (^)(NSError *error))fail timeoutInterval:(NSTimeInterval)timeoutInterval
{
    [VPOS_LM locateSuccessWithAddress:^(CLLocationCoordinate2D userLocationCoordinate,NSDictionary *address){
        success(userLocationCoordinate,address);
    }Fail:^(NSError *error){
        fail(error);
    }timeoutInterval:timeoutInterval];

}
/**
 * 根据经纬度显示地图
 */
- (void) showMapWithLongitude:(CLLocationDegrees)longitude latitude:(CLLocationDegrees)latitude
{
    //    if (self.hpUtilDelegate && [self.hpUtilDelegate respondsToSelector:@selector(showMapWithLongitude:latitude:)]) {
    //        CLLocationDegrees longitude = [[degreesDic objectForKey:@"longitude"] doubleValue];
    //        CLLocationDegrees latitude = [[degreesDic objectForKey:@"latitude"] doubleValue];
    //        [self.hpUtilDelegate showMapWithLongitude:longitude latitude:latitude];
    //    }
}
@end
